package server.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import server.config.ServerConfig;
import server.db.SQL;

public class FeuerwehrenImAlarmierungenTableUpdaten {

	
private static Logger logger = Logger.getLogger(CacheTableNeuErstellen.class);
	
	public static void main(String[] args) {

		PropertyConfigurator.configure("log4J.cfg");
		try {
			new ServerConfig("serverConfigLocal.cfg");
			SQL.getInstance();

			try {
				PreparedStatement stmt;
				stmt = SQL.getInstance().getConPool().getConnectionFromPool().prepareStatement("SELECT id, feuerwehrid FROM `alarmierungen`");

				ResultSet rs = stmt.executeQuery();

				while (rs.next()) {

					
					if (rs.getInt("id") < 93000) {
						continue;
					}
					System.out.println(rs.getInt("id"));
					
					Connection con = SQL.getInstance().getConPool().getConnectionFromPool();
					PreparedStatement stmt2 = con
							.prepareStatement("SELECT alarmkennung FROM alarmierteschleifen WHERE alarmid = '" + rs.getInt("id") + "'");
					ResultSet rs2 = stmt2.executeQuery();
					List<Integer> list = new ArrayList<>();
					while (rs2.next()) {
						list.add(SQL.getFeuerwehrIdByAlarmValue(rs2.getString("alarmkennung")));
					}
					stmt2.close();
					SQL.getInstance().getConPool().returnConnectionToPool(con);
					
					
					if(list.size() > 0 && list.get(0) != -1) {
						boolean alleGleich = false;
						int lastWert = list.get(0);
						for(int i:list) {
							if(lastWert == i) {
								alleGleich = true;
							}
							else {
								alleGleich = false;
								break;
							}
						}
						
						if(alleGleich) {
							
							if(list.get(0) != rs.getInt("feuerwehrid")) {
							System.out.println(list);
								Connection con2 = SQL.getInstance().getConPool().getConnectionFromPool();
								PreparedStatement stmt3 = con2
										.prepareStatement("UPDATE `alarmierungen` SET feuerwehrid = '"+list.get(0)+"' WHERE id = '" + rs.getInt("id") + "'");
								stmt3.executeUpdate();
								stmt3.close();
								SQL.getInstance().getConPool().returnConnectionToPool(con2);
								SQL.getInstance().addAlarmShowTable(rs.getInt("id"));
							}
						}
						else {
							System.out.println(list);
						}
					}
					

				}
			} catch (SQLException e) {
				logger.error("SQLException", e);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
}
}